package cn.edu.hit;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpRequestorWithTokenForJoinsystem extends HttpRequestorForJoinsystem {
    private Token token;
    private final String token_aquire_url;
    private final String token_aquire_user;
    private final String token_aquire_password;


    private HttpRequestorWithTokenForJoinsystem(String token_aquire_url, String token_aquire_user, String token_aquire_password) {
        this.token_aquire_url = token_aquire_url;
        this.token_aquire_user = token_aquire_user;
        this.token_aquire_password = token_aquire_password;
    }

    private static HashMap<String, HttpRequestorWithTokenForJoinsystem> requestorPool = new HashMap<>();

    public static HttpRequestorWithTokenForJoinsystem getInstance(String token_aquire_url, String token_aquire_user, String token_aquire_password) {
        String key = token_aquire_url + token_aquire_user + token_aquire_password;
        if (requestorPool.containsKey(key)) {
            return requestorPool.get(key);
        }
        HttpRequestorWithTokenForJoinsystem requestorWithToken = new HttpRequestorWithTokenForJoinsystem(token_aquire_url, token_aquire_user, token_aquire_password);
        requestorPool.put(key, requestorWithToken);
        return requestorWithToken;
    }

    public void aquireToken() throws Exception {
        if (token == null) {
            token = this.aquireToken(token_aquire_url, token_aquire_user, token_aquire_password);
        }
//        if (!token.isValid()){
//            token = this.refreshToken(token_refresh_url,token);
//            token =  this.aquireToken(token_aquire_url,token_aquire_user,token_aquire_password);
//        }
    }

    public String getFeatures(String url, long fromTime, long endTime, boolean sort, String... ports) throws Exception {
        this.aquireToken();
        return this.getFeatures(url, token, null, fromTime, endTime, sort, ports);
    }

    public String putResults(String url, List<Map.Entry<Long, String>> faults) throws Exception {
        this.aquireToken();
        return this.putResults(url, token, faults);
    }

    @Override
    public String doGet(String url) throws Exception {
        this.aquireToken();
        String resultJson = super.doGet(url, token.token);
        JSONObject jsonObject = JSONObject.fromObject(resultJson);
        String code = jsonObject.optString("code");
        if (code == "AUTH00001") {
            token = this.aquireToken(token_aquire_url, token_aquire_user, token_aquire_password);
            return super.doGet(url, token.token);
        }
        return resultJson;
    }

    @Override
    public String doPost(String url, String json) throws Exception {
        this.aquireToken();
        return super.doPost(url, token, json);
    }

}
